package com.rolerealm.common.util;

import com.rolerealm.common.constant.ErrorCode;
import com.rolerealm.common.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Date;

@Component
public class JwtUtil {

    private final SecretKey secretKey;
    private final long expiresInSeconds;

    public JwtUtil(
            @Value("${jwt.secret}") String secret,
            @Value("${jwt.expires-in}") long expiresInSeconds
    ) {
        // Ensure key length is sufficient for HS256
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        this.secretKey = Keys.hmacShaKeyFor(keyBytes);
        this.expiresInSeconds = expiresInSeconds;
    }

    public String generateToken(Long userId, String username, Duration ttl) {
        long ttlSeconds = ttl != null ? ttl.toSeconds() : expiresInSeconds;
        Date now = new Date();
        Date exp = new Date(now.getTime() + ttlSeconds * 1000);
        return Jwts.builder()
                .setSubject(String.valueOf(userId))
                .claim("username", username)
                .setIssuedAt(now)
                .setExpiration(exp)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
    }

    public Claims parse(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(secretKey)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (io.jsonwebtoken.ExpiredJwtException e) {
            throw new BusinessException(ErrorCode.USER_TOKEN_EXPIRED);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.USER_TOKEN_INVALID);
        }
    }

    public Long extractUserIdFromAuthorization(String authorizationHeader) {
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED);
        }
        String token = authorizationHeader.substring(7);
        Claims claims = parse(token);
        try {
            return Long.parseLong(claims.getSubject());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.USER_TOKEN_INVALID);
        }
    }
}


